package com.glsc.ngateway.opmanage.service;

import com.alibaba.excel.util.CollectionUtils;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Role;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
//import com.glsc.ngateway.common.api.platform.dto.it.command.PageQueryParamDto;
import com.glsc.ngateway.common.api.common.dto.PageQueryParamDto;
import com.glsc.ngateway.opmanage.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.RoleRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.UserRoleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/3 13:17
 */
@Service
public class RoleService {

    private RoleRepo roleRepo;
    private UserRoleRepo userRoleRepo;

    @Autowired
    public void setRoleRepo(RoleRepo roleRepo) {
        this.roleRepo = roleRepo;
    }

    @Autowired
    public void setUserRoleRepo(UserRoleRepo userRoleRepo) {
        this.userRoleRepo = userRoleRepo;
    }

    @Resource
    private UserService userService;

    @Transactional
    public Role add(Role role) {
        if (role.getId() != null) {
            throw PlatformException.error("新增角色不要输入id");
        }
        return roleRepo.save(role);
    }

    public Role findById(long id) {
        return roleRepo.findById(id).orElse(null);
    }

    public Role save(Role role) {
        return roleRepo.save(role);
    }

    public List<Role> getByName(String name){
        return roleRepo.queryByName(name);
    }

    @Transactional
    public void addUsers(long roleId, List<Long> userIds) {
        userIds.forEach(id -> userRoleRepo.addUserRole(id, roleId));
    }

    @Transactional
    public void deleteUsers(long roleId, List<Long> userIds) {
        userIds.forEach(id -> userRoleRepo.deleteUserRole(id, roleId));
    }

    @Transactional
    public Role update(Role role) {
        if (role.getId() == null) {
            throw PlatformException.error("角色id不能为空");
        }
        Role existRole = roleRepo.queryByIdLock(role.getId());
        if (existRole == null) {
            throw PlatformException.error("未找到id=" + role.getId() + "的角色");
        }
        role.setUrls(existRole.getUrls());
        return roleRepo.save(role);
    }

    public int delete(long id) {
        userRoleRepo.deleteById(id);
        return roleRepo.deleteById(id);
    }


    public List<Role> findAll() {
        return roleRepo.findAll();
    }

    public List<Role> findAll(Specification s) {
        return roleRepo.findAll(s);
    }

    public Page<Role> findPage(int page, int size) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = PageRequest.of(page - 1, size, direction, sort);
        return roleRepo.findAll(pageable);
    }

    public Page<Role> findPage(Specification s, int page, int size) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = PageRequest.of(page - 1, size, direction, sort);
        return roleRepo.findAll(s, pageable);
    }

    /**
     * 根据权限id分页查询角色
     * @param param
     * @return
     */
    public Page<Role> findPageByAuthId(PageQueryParamDto<Map<String,Object>> param) {
        Pageable pageable = param.getPageable();
        Object authId = param.getParam().get("authId");
        Object name = param.getParam().get("name");
        Page<Role> page = roleRepo.page(pageable, (long)authId, (String)name);
        return page;
    }


    /**
     * 根据RoleName找员工
     */
    public List<String> getUsersByRole(@NotNull String roleName) {
        return this.getByName(roleName)
                .stream()
                .map(role -> userService.findByRoleId(role.getId()))
                .filter(users -> !CollectionUtils.isEmpty(users))
                .flatMap(item -> item.stream().map(User::getUsername))
                .collect(Collectors.toList());
    }
}
